package com.hyw.encryption.utils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.util.ReflectionUtils;

public class AESUtils {
  private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

  public static String base64Encode(byte[] bytes) {
    return Base64.getEncoder().encodeToString(bytes);
  }

  public static byte[] base64Decode(String base64Code) {
    return Base64.getDecoder().decode(base64Code);
  }

  public static byte[] aesEncryptToBytes(String content, String encryptKey) {
    byte[] ret = null;
    try {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(128);
      Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
      cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
      ret = cipher.doFinal(content.getBytes("utf-8"));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
        | BadPaddingException | UnsupportedEncodingException e) {
      ReflectionUtils.rethrowRuntimeException(e);
    }
    return ret;
  }

  public static String aesEncrypt(String content, String encryptKey) {
    return base64Encode(aesEncryptToBytes(content, encryptKey));
  }

  public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) {
    String ret = null;
    try {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(128);
      Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
      cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
      byte[] decryptBytes = cipher.doFinal(encryptBytes);
      ret = new String(decryptBytes);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
        | BadPaddingException e) {
      ReflectionUtils.rethrowRuntimeException(e);
    }
    return ret;
  }

  public static String aesDecrypt(String encryptStr, String decryptKey) {
    return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
  }

}